//
//  ErandDetailListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-8-16.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "ErandDetailListViewController.h"
#import "LStoreProblemListViewController.h"
#import "RejectViewController.h"
#import "MTStatusBarOverlay.h"

@interface ErandDetailListViewController () <RejectViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *applyList;
@property (nonatomic, strong) NSMutableDictionary *selectedRowDict; //选中的行
@property (nonatomic, assign) BOOL hasSelectedRow; //是否有选中的行
@property (nonatomic, assign) NSInteger selectedRow;
@property (nonatomic, assign) BOOL isallselectedRow;
- (IBAction)rejectAllApplyAction:(id)sender;
- (IBAction)agreeAllApplyAction:(id)sender;

@end

@implementation ErandDetailListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.selectedRowDict = [NSMutableDictionary dictionary];
    self.hasSelectedRow = NO;
    self.selectedRow =0;
    self.isallselectedRow = NO;
    self.applyList = [NSMutableArray array];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = YES;
    
    self.title = @"申请明细审批";
    [super viewWillAppear:animated];
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    [self.rightBtn addTarget:self action:@selector(rightNavItemAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateHighlighted];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateSelected];
    [self.rightBtn addTarget:self action:@selector(selectRowAction:event:) forControlEvents:UIControlEventTouchUpInside];
    [self performSelector:@selector(refreshViewByReloadData) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    if ([self.dudaoInfo count] > 0) {
        NSString *gh = [self.dudaoInfo objectForKeyOrNil:@"gh"];
        [self getApplyDetailListOfDudao:gh];
    }
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getApplyDetailListOfDudao:(NSString *)gh {
    if ([gh length] > 0 && !self.isRefreshing) {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"]; //领导工号
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gh,@"gh",
                               gonghao,@"ldgh", nil];
        [self.networkManager requestWithMethod:showAppListByGh parameter:param delegate:self];
        [self.HUD show:YES];
        self.isRefreshing = YES;
    }
}

- (IBAction)rejectAllApplyAction:(id)sender {
    if(self.selectedRow == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请至少选择一项"
                                                       delegate:self
                                              cancelButtonTitle:@"我知道了"
                                              otherButtonTitles: nil];
        [alert show];

    } else {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    RejectViewController *rejectVC = (RejectViewController *)[storyboard instantiateViewControllerWithIdentifier:@"RejectViewController"];
    rejectVC.delegate = self;
    [self addChildViewController:rejectVC];
    [self.view addSubview:rejectVC.view];
    }
}

- (IBAction)agreeAllApplyAction:(id)sender {
    if(self.selectedRow == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请至少选择一项"
                                                       delegate:self
                                              cancelButtonTitle:@"我知道了"
                                              otherButtonTitles: nil];
        [alert show];
        
    } else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:@"您确认审批通过所选的出差申请吗？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    alert.tag = 10002;
    [alert show];
    }
}

#pragma mark - UIAlerViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        NSInteger tag = alertView.tag;
        if (tag == 10001) {
            
        } else if (tag == 10002) { //全部通过
            [self agreeAllApply];
        }
    }
}

- (void)rejectAllApplyWithReason:(NSString *)reason {
    NSString *pcArray = @"";
    for (int i =0; i < [self.applyList count]; i ++) {
        if ([[self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:i]] boolValue]) {
        NSDictionary *info = [self.applyList objectAtIndex:i];
        NSString *applyId = [info objectForKeyOrNil:@"pc"];
        if ([pcArray length] == 0) {
            pcArray = [NSString stringWithFormat:@"%@",applyId];
        } else if ([pcArray length] > 0) {
            pcArray = [pcArray stringByAppendingFormat:@",%@",applyId];
        }
        }
    }
    
    if ([pcArray length] > 0) {
//        UserInfo *user = [UserInfo instance];
//        NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"]; //领导工号
        NSString *gonghao = [self.dudaoInfo objectForKeyOrNil:@"gh"]; //督导工号
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               pcArray,@"pcArray",
                               reason,@"bhly",
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:rejectAllApplyList parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

- (void)agreeAllApply {
    NSString *ids = @"";
    for (int i =0; i < [self.applyList count]; i ++) {
        if ([[self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:i]] boolValue]) {
        NSDictionary *info = [self.applyList objectAtIndex:i];
        NSString *applyId = [NSString stringWithFormat:@"%@",[info objectForKeyOrNil:@"id"]];
        if ([applyId length] > 0) {
            if ([ids length] == 0) {
                ids = applyId;
            } else if ([ids length] > 0) {
                ids = [ids stringByAppendingFormat:@",%@",applyId];
            }
        }
        }
    }
    
    if ([ids length] > 0) {
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               ids,@"ids", nil];
        [self.networkManager requestWithMethod:examineApply parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

#pragma mark - RejectViewDelegate
- (void)reject:(RejectViewController *)rejectVC willRejctWithReason:(NSString *)content {
    [self rejectAllApplyWithReason:content];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if (methodId == showAppListByGh) { //申请详情
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                [self.applyList removeAllObjects];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *results = [dataObject objectForKeyOrNil:@"applyList"];
                        if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                            [self.applyList  addObjectsFromArray:results];
                        }
                    } else if ([dataObject isKindOfClass:[NSArray class]]) {
                        [self.applyList addObjectsFromArray:dataObject];
                    }
                }
                
                [self.tableView reloadData];
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"出差申请明细列表获取失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    } else if (methodId == examineApply) { //全部通过
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                    if (resultCode == 1) {
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差申请审批成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;
                        
                        [self showAlertViewWithMessage:@"出差申请审批成功"];
                        
                        [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                    }
                }
            }
        }
    } else if (methodId == rejectAllApplyList) { //全部驳回
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    NSInteger resultCode = [[dataObject objectForKeyOrNil:@"reslut"] integerValue];
                    if (resultCode == 1) {
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差申请全部驳回成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;
                        
                        [self showAlertViewWithMessage:@"出差申请驳回成功"];
                        
                        [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                    }
                }
            }
        }
    }
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == showAppListByGh) {
                msg = @"出差申请明细列表获取失败，请稍后重试";
            } else if (methodId == examineApply) {
                msg = @"出差申请审批失败，请稍后重试";
            } else if (methodId == rejectAllApplyList) {
                msg = @"出差申请全部驳回失败，请稍后重试";
            }
            
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.applyList count];
//    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ErrandsApplyDetailCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    UIButton *selectBtn = (UIButton *)[cell.contentView viewWithTag:100];
    UILabel *erandPcLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dudaoNameLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *dudaoGhLbl = (UILabel *)[cell.contentView viewWithTag:104];
    UILabel *dudaoZwLbl = (UILabel *)[cell.contentView viewWithTag:105];
    UILabel *jxsNameLbl = (UILabel *)[cell.contentView viewWithTag:106];
    UILabel *jxsCodeLbl = (UILabel *)[cell.contentView viewWithTag:107];
    UILabel *erandReasonLbl = (UILabel *)[cell.contentView viewWithTag:108];
    UILabel *erandPlaceLbl = (UILabel *)[cell.contentView viewWithTag:109];
    NSLog(@"@@@@@@@@@@@@@@@@@%d",self.selectedRow);
    NSInteger row = indexPath.row;
    
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        NSString *pc = [cellData objectForKeyOrNil:@"pc"];
        NSString *erandDate = [cellData objectForKeyOrNil:@"ccsj"];
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *dept = [cellData objectForKeyOrNil:@"zw"];
        NSString *jxsName = [cellData objectForKeyOrNil:@"jxsmc"];
        NSString *jxsCode = [cellData objectForKeyOrNil:@"jxsdm"];
        NSString *reason = [cellData objectForKeyOrNil:@"ccmd"];
        NSString *place = [cellData objectForKeyOrNil:@"ccdd"];

        if ([pc length] == 0) {
            pc = @"";
        }
        if ([erandDate length] == 0) {
            erandDate = @"";
        }
        if ([dudaoName length] == 0) {
            dudaoName = @"";
        }
        if ([dudaoCode length] == 0) {
            dudaoCode = @"";
        }
        if ([dept length] == 0) {
            dept = @"";
        }
        if ([jxsName length] == 0) {
            jxsName = @"";
        }
        if ([jxsCode length] == 0) {
            jxsCode = @"";
        }
        if ([reason length] == 0) {
            reason = @"";
        }
        if ([place length] == 0) {
            place = @"";
        }
        
        erandPcLbl.text = pc;
        dateLbl.text = erandDate;
        dudaoNameLbl.text = dudaoName;
        dudaoGhLbl.text = dudaoCode;
        dudaoZwLbl.text = dept;
        jxsNameLbl.text = jxsName;
        jxsCodeLbl.text = jxsCode;
        erandReasonLbl.text = reason;
        erandPlaceLbl.text = place;
        
    }
//    
   [selectBtn addTarget:self action:@selector(selectRowAction:event:) forControlEvents:UIControlEventTouchUpInside];

    if ([self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]]) {
        BOOL selected = [[self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]] boolValue];
        if (selected) {
            [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
        } else {
            [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
        }
    } else {
        [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
        [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateSelected];
    }
    [selectBtn setSelected:NO];
    return cell;
    
}

#pragma mark - IBAction methods
- (void)selectRowAction:(id)sender event:(id)event {
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath == nil) {
        return;
    }
    int row = indexPath.row;
    
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    NSLog(@"!!!!!!!!!!11111%d",tag);
    if (tag == 100) { //选中、取消选中行
        NSLog(@"!!!!!!!!!!22222");
        BOOL selected = YES;
        if ([self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]]) {
            BOOL value = [[self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]] boolValue];
            selected = !value;
        }
        [self.selectedRowDict setObject:[NSNumber numberWithBool:selected] forKey:[NSNumber numberWithInt:row]];
        if (selected) {
            self.selectedRow++;
        } else{
            self.selectedRow--;
        }
        BOOL hasSelected = NO;
        NSArray *keys = [self.selectedRowDict allKeys];
        for (int i = 0; i < [keys count]; i ++) {
            NSString *key = [keys objectAtIndex:i];
            BOOL value = [[self.selectedRowDict objectForKeyOrNil:key] boolValue];
            if (value) {
                hasSelected = YES;
                break;
            }
        }
        self.hasSelectedRow = hasSelected;
        [self.tableView reloadData];
    }
}


- (void)rightNavItemAction:(id)sender {
 NSLog(@"!!!!!!!!!!!!!!!!!!@%d",self.isallselectedRow);
    if (!self.isallselectedRow) {
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
        self.isallselectedRow = YES;
        self.hasSelectedRow = YES;
        self.selectedRow = self.applyList.count;
    } else {
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@!!!11111");
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
        self.isallselectedRow = NO;
        self.hasSelectedRow = NO;
        self.selectedRow = 0;
    }
    for (int i =0; i < [self.applyList count]; i ++) {
        [self.selectedRowDict setObject:[NSNumber numberWithBool:self.isallselectedRow] forKey:[NSNumber numberWithInt:i]];
    }
    [self.tableView reloadData];
}


#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 74.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    LStoreProblemListViewController *storeProblemVC = (LStoreProblemListViewController *)[storyboard instantiateViewControllerWithIdentifier:@"LeaderStoreProblemList"];
    storeProblemVC.viewType = EnterFromCCSQ; //标识从出差申请明细界面进入
    NSInteger row = indexPath.row;
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        storeProblemVC.erandInfo = cellData;
    }
    [self.navigationController pushViewController:storeProblemVC animated:YES];
}

@end
